package com.sinopec.basemodule.camera;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.gyf.immersionbar.ImmersionBar;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraView;
import com.sinopec.basemodule.R;
import com.sinopec.basemodule.camera.model.CameraConfig;
import com.sinopec.basemodule.camera.utils.CameraUtils;
import com.sinopec.basemodule.common.Logger;
import com.sinopec.basemodule.http.ExceptionEngine;
import com.sinopec.basemodule.utils.ToastUtils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 拍照基本流程
 */
public class CameraActivity extends AppCompatActivity {
    public static final String DIRECTORY_NAME = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
            + File.separator + "Camera";

    /**
     * 拍照请求code
     */
    public static final int REQUEST_CODE = 10010;
    /**
     * 照片地址
     */
    public static final String IMAGE_URL = "IMAGE_URL";

    CompositeDisposable mDisposables = new CompositeDisposable();
    private CameraView mCamera;
    private CameraListener mCameraListener;
    /**
     * 拍照按钮
     */
    private ImageView mCameraCaptureIv;
    /**
     * 取消按钮
     */
    private TextView mCancelTv;
    /**
     * 是否正在拍照
     */
    private boolean mTakingPhoto = false;

    public static void startActivity(AppCompatActivity activity) {
        activity.startActivityForResult(new Intent(activity, CameraActivity.class), REQUEST_CODE);
    }

    public static void startActivity(Fragment fragment) {
        fragment.startActivityForResult(new Intent(fragment.getContext(), CameraActivity.class), REQUEST_CODE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        if (window != null) {
            window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        setContentView(R.layout.activity_camera);

        ImmersionBar.with(this).init();

        //申请动态权限
        apply4DynamicPermissions();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCamera.removeCameraListener(mCameraListener);
        mDisposables.clear();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            //预览界面显示图片地址
            if (!data.hasExtra(IMAGE_URL)) {
                return;
            }
            String imageUrl = data.getStringExtra(IMAGE_URL);
            Intent intent = new Intent();
            intent.putExtra(CameraActivity.IMAGE_URL, imageUrl);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    /**
     * 初始化Camera
     */
    private void initCameraFragment() {
        //添加预览界面
        mCamera = findViewById(R.id.camera);
        mCameraCaptureIv = findViewById(R.id.camera_capture_iv);
        mCancelTv = findViewById(R.id.cancel_tv);

        mCamera.setLifecycleOwner(this);
        mCamera.clearCameraListeners();
        mCameraListener = new CameraListener() {
            @Override
            public void onPictureTaken(byte[] jpeg) {
                //拍照结束后置为false
                mTakingPhoto = false;
                onPicture(jpeg);
            }
        };
        mCamera.addCameraListener(mCameraListener);

        initEvent();
    }

    /**
     * 获得拍照数据
     */
    @SuppressLint("CheckResult")
    private void onPicture(byte[] jpeg) {
        if (jpeg == null) {
            return;
        }
        //保存图片
        Observable.just(jpeg)
                .subscribeOn(Schedulers.io())
                .map(new Function<byte[], File>() {
                    @Override
                    public File apply(byte[] bytes) throws Exception {
                        //保存为文件

                        //1.创建文件
                        File file = CameraUtils.getOutputMediaFile(CameraActivity.this, CameraConfig.MEDIA_ACTION_PHOTO, DIRECTORY_NAME, null);

                        //2.保存到文件
                        FileOutputStream fileOutputStream = null;
                        try {
                            fileOutputStream = new FileOutputStream(file);
                            fileOutputStream.write(bytes);
                        } finally {
                            if (fileOutputStream != null) {
                                fileOutputStream.close();
                            }
                        }

                        try {
                            //3.扫描相册，让图片在相册中显示
                            MediaScannerConnection.scanFile(CameraActivity.this, new String[]{file.getAbsolutePath()}, null,
                                    new MediaScannerConnection.OnScanCompletedListener() {
                                        @Override
                                        public void onScanCompleted(String path, Uri uri) {

                                        }
                                    });
                        } catch (Exception ignore) {

                        }
                        return file;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        if (CameraActivity.this.isFinishing()) {
                            return;
                        }
                        Logger.d("123===", "c   " + Thread.currentThread().getName());
                        //跳转到预览界面
                        CameraPreviewActivity.startActivityForResult(CameraActivity.this, file.getAbsolutePath(), REQUEST_CODE);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable e) throws Exception {
                        if (CameraActivity.this.isFinishing()) {
                            return;
                        }
                        if (e != null && e.getMessage() != null) {
                            if (e instanceof ExceptionEngine.ResponseThrowable) {
                                ExceptionEngine.ResponseThrowable newE = (ExceptionEngine.ResponseThrowable) e;
                                ToastUtils.showToast(newE.getMessage());
                            } else {
                                ToastUtils.showToast(e.getMessage());
                            }
                        }
                    }
                });
    }

    private void initEvent() {
        //取消按钮
        mCancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //拍照按钮
        mCameraCaptureIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePhoto();
            }
        });
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        //Size pictureSize = mCamera.getPictureSize();
        //如果正在拍照，拦截
        if (mTakingPhoto) {
            return;
        }
        mTakingPhoto = true;
        mCamera.capturePicture();
    }

    /**
     * 申请动态权限
     */
    private void apply4DynamicPermissions() {
        //申请动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Manifest.permission.RECORD_AUDIO
            RxPermissions rxPermissions = new RxPermissions(this);
            Disposable disposable = rxPermissions.requestEachCombined(
                    Manifest.permission.CAMERA
                    , Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.READ_EXTERNAL_STORAGE
            )
                    .subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) throws Exception {
                            if (permission.granted) {
                                //授权成功
                                initCameraFragment();
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                //授权点击了不再提醒
                                Toast.makeText(CameraActivity.this, "需要访问你的相机来拍照，请在“系统设置”中允许“使用相机”权限。", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                //取消授权
                                Toast.makeText(CameraActivity.this, "需要访问你的相机来拍照，请在授权对话框中允许“使用相机”权限。", Toast.LENGTH_SHORT).show();
                                finish();
                            }
                        }
                    });
            mDisposables.add(disposable);
        } else {
            initCameraFragment();
        }
    }

}
